<template>
    <div class="order-list-item" v-if="Array.isArray(orderItem.list)">
        <no-data v-if="orderItem.list.length == 0"  :noDataProps="{text:'暂无相关的订单哦'}"></no-data>
        <div v-else>
            <scroller ref="myscroller"
                      :on-refresh="refresh"
                      :on-infinite="infinite">
                <div class="sub-store-msg-box" v-for="orderValue in orderItem.list" @click="selectStore(orderValue.orderNum,orderValue.selected)">
                <div class="displayFlex sub-store-msg" >
                    <div v-if="!orderItem.noSelectBtn && orderItem.orderState == 0" class="displayFlex flex-algin-center select-wImg">
                        <span v-if="false" class="disabled-select"></span>
                        <img class="select-img"
                             v-else-if="orderValue.selected"
                             src="../../../assets/images/cart/cart_select.png" alt="">
                        <img class="select-img"
                             v-else src="../../../assets/images/cart/cart_not_select.png" alt="">
                    </div>
                    <div class="flex1 displayFlex flex-algin-center justifyCtBwt positionR">
                    <span class="displayFlex flex-algin-center">
                        <router-link class="displayFlex header-wrap" :to="{path:'/store',query:{storeId:orderValue.storeId}}">
                            <span class="cart-userheader-wimg">
                                <img class="cart-userheader-img positionAbCenter" :src="orderValue.storeLogo"
                                     alt="">
                            </span>
                            <span class="cart-user-name">{{orderValue.storeName}}</span>
                        </router-link>
                        <router-link :to="{path:'/im/chat',query:{storeId:orderValue.storeId}}" class="order-server-wicon">
                            <img class="order-server-icon" src="../../../assets/images/order/order_server_icon.png" alt="">
                        </router-link>
                        <div class="order-wclock" v-if="orderValue.remainPayMs">
                            <img class="order-clock" src="../../../assets/images/order/order_clock.png" alt="">
                            <day-hmsm :timerProp="{expStartTime:orderValue.remainPayMs,showTime:{day:false,hour:false,minute:true,second: true,ms: true},timeSymbol:':'}"></day-hmsm>
                        </div>
                    </span>
                        <!--<span v-if="cartMoudleKey == 'cartStoreInfos'">-->
                        <!--<span v-if="cartStoreInfo.upportExpress" class="cart-send-way">支持快递与自提</span>-->
                        <!--<span v-else class="cart-send-way">仅支持自提</span>-->
                        <!--</span>-->
                    </div>
                </div>
                <order-item class="order-goods-wrap" :orderItemProp="orderValue" v-if="orderValue.orderItemModels.length == 1"></order-item>
                <div class="goods-box-wrap" v-else>
                    <goods-box class="goods-box" :goodsBoxsProp="detailGoodsBox(orderValue.orderItemModels)"></goods-box>
                    <div class="goods-num-count">件数：{{orderValue.orderItemModels.length}}</div>
                </div>
                <div class="operate-btn-wrap displayFlex justifyCtBwt">
                    <span class="operate-btn-left displayFlex flex-algin-center">总额：￥{{orderValue.orderAmount}}</span>
                    <span class="operate-btn-right" v-if="orderValue.orderOperateItems">
                    <span class="operate-btn" :class="btnClass(item.tag)" @click.stop="clickOrderBtn(item,orderValue)"  v-for="item in orderValue.orderOperateItems">{{item.desc}}</span>
                </span>
                </div>
            </div>
            </scroller>
        </div>
    </div>
</template>

<script>
    export default {
        name: "OrderItemList",
        props: {
            orderProp: Object
        },
        data() {
            return {
                goodsBox:{
                    isNeedScroll: false,//是否需要滚动条
                    list:[/*@list boxitem的列表个数*/
                        // {
                        //     storeId:1,
                        //     type:1,//1表示两端布局，价格和卖出商品量,2表示一边是评价一边是日期
                        //     itemId:0,//商品id
                        //     currency:"",/*金币的符号*/
                        //     url:'https://oss.pg.yibaotong.top/thumbnails/item/2018711_offline/527176524100.jpg',/*@url 图片或者视频的url*/
                        //     itemTitle:'13232',/*@description 描述*/
                        //     price:'1212',/*@description 价格*/
                        //     buyerNum:'',/*@buyerNum 已购买件数*/
                        //     time:0,/*@time时间，当type为2时填写*/
                        // }
                    ],
                },
                orderItem: {
                    "noSelectBtn": false,      //-------是否需要选中圆圈
                    // list: [{
                    //     "selected": false,
                    //     "orderNum": "TR_19040384382004pp",      //-------订单号
                    //     "storeId": 527,         //---------店铺ID
                    //     "storeName": "木木木欧诺",     //-----------店铺名字
                    //     "storeLogo": "http://asd/190b4a495f5fff.jpg",     //----------店铺logo
                    //     "orderState": 1,       //-----订单的状态, 0:未付款, 1:已付订金（待通知提货|待发货）,2:待提货 | 待收货,3:交易完成  4:退款待卖家同意 5：退款待打款 6:退款完成 -1:交易关闭(拍卖单超时未支付) -2：订单失效（超时） -3：买家取消（未付款订单）
                    //     "stateDesc": "等待通知提货",          //----------订单状态描述
                    //     "deliveryType": 0,                   //----------订单配送类型  0, 到店提货  1, 同城快递
                    //     "waitingActResult": false,          //----------是否等待活动结果
                    //     "remainPayMs": 0,               //-------------剩余支付毫秒数
                    //     "orderAmount": "8872.4",        //-------------订单总额
                    //     "depositAmount": "8872.4",      //-------------保证金总额
                    //     "expressFreight": "8872.4",     //-------------运费
                    //     "userPayAmount": "887",         //-------------用户已付金额
                    //     "lastAmount": "7985.4",         //--------订单尾款（自提、待提货 且尾款为0，显示我要提货，点击展示提货码）
                    //     "deliveryQrCode": "order@delivery@code@TR@123@345",      //---------订单提货码（自提订单且待提货状态才有效）
                    //     "orderItemModels": [            //-------------订单商品列表
                    //         {
                    //             "itemId": 1787,         //------------商品ID
                    //             "itemPhoto": "item/20175_offline/113685234100.png",     //---------商品图片
                    //             "itemName": "哈哈，这个好",       //---------商品名称
                    //             "styleName": "",        //--------购买款式
                    //             "buyNum": 1,        //-------商品购买数量
                    //             "itemPrice": "8872.4"       //----------商品售价
                    //         }
                    //     ],
                    //     "orderOperateItems": [          //----------订单操作按钮项
                    //         {
                    //             "type": 0,          //------操作项类型：0-功能按钮 1-下拉按钮  2-纯文字
                    //             "tag": "delete_order",      //------操作项标识
                    //             "desc": "删除订单",     //-------文字描述
                    //             "sonItems": null        //-------子项目列表(下拉按钮有效)
                    //         },
                    //     ]
                    // }]
                }
            }
        },
        mounted() {
            this.orderItem = Object.assign({}, this.orderItem, this.orderProp);
            // console.log(this.orderProp)
        },
        methods: {
            detailGoodsBox(item){
                let tempObj = {};
                let tempList = [];
                let that = this;
                if(Array.isArray(item) && item.length > 0 ){
                    item.forEach((itemValue,itemIndex)=>{
                        tempObj = {
                            storeId:that.storeId,
                            type:1,//1表示两端布局，价格和卖出商品量,2表示一边是评价一边是日期
                            itemId:itemIndex.itemId,//商品id
                            currency:"￥",/*金币的符号*/
                            url:itemValue.itemPhoto,/*@url 图片或者视频的url*/
                            itemTitle:itemValue.itemName,/*@description 描述*/
                            price:itemValue.itemPrice,/*@description 价格*/
                            buyerNum:itemValue.buyNum,/*@buyerNum 已购买件数*/
                        }
                        tempList.push(tempObj);
                    })
                }
                let returnObj = {
                    isNeedScroll: false,//是否需要滚动条
                    list:tempList,//是否需要滚动条
                };
                return returnObj;
            },
            /*选择某个店铺下面所有的商品*/
            selectStore(orderNum, isSelected) {
                let that = this;
                this.orderItem.list.forEach((value, index) => {
                    if (value.orderNum == orderNum) {
                        isSelected = !isSelected;
                        that.orderItem.list[index].selected = isSelected;
                    }
                })
                that.orderItem.list.splice(0, 1, that.orderItem.list[0]);
                /*刷新购买商品的价格*/
                this.refreshBuyBar(orderNum);
            },
            /*订单剩余的支付时间*/
            surplusPayTime(){
                // that.orderItem.list.forEach((value,index)=>{
                //     console.log(index);
                // })
            },
            /**/

            /*点击订单*/
            clickOrderBtn(item,orderValue){
                let that = this;
                let url = '';
                switch (item.tag) {
                    case 'cancel_order':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/cancel`;that.userOperateOrder(url,'put');break;//取消订单
                    /*todo*/
                    case 'pay_order':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.userOperateOrder(url,'put');break;//支付订单
                    case 'delete_order':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.userOperateOrder(url,'delete');break;//删除订单
                    /*todo*/
                    case 'buy_again':that.openHKHWConfirm('购买需要下载好看好玩');break;//再次购买
                    case 'apply_refund':that.openHKHWConfirm('申请退款需要下载好看好玩');break;//申请退款
                    case 'cancel_refund':url = `${that.NW_API_API_LOCALE_VERSION}/order/refund/cancle?orderNum=${orderValue.orderNum}`;that.userOperateOrder(url,'put');break;//撤销退款
                    case 'view_delivery':that.openHKHWConfirm('查看物流需要下载好看好玩');break;//查看物流
                    /*todo 没有接口*/
                    case 'urge_delivery':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.openHKHWConfirm('催货需要下载好看好玩');break;//催货
                    /*todo 没有接口*/
                    case 'remind_delivery':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.openHKHWConfirm('提醒发货需要下载好看好玩');break;//提醒发货
                    /*todo 没有接口*/
                    case 'apply_after_sale':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.openHKHWConfirm('申请售后需要下载好看好玩');break;//申请售后
                    case 'gift_non_refund':that.$root.$emit('toast',{'msg':'定制礼品不可退款'});break;//礼品不可退款
                    /*todo*/
                    case 'pickup_code':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/user/${that.userId}/delete`;that.openHKHWConfirm('获取取码需要下载好看好玩');break;//获取取码
                    case 'confirm_receive':url = `${that.NW_API_API_LOCALE_VERSION}/order/${orderValue.orderNum}/confirm/receive`;that.userOperateOrder(url,'put');break;//确认收货
                    default:that.openHKHWConfirm('此操作需要下载好看好玩');break;
                }
            },
            /*按钮的样式*/
            btnClass(tag){
                let style = ''
                switch (tag) {
                    case 'apply_refund':style = 'refund-style';break;//取消订单
                    case 'delete_order':style = 'refund-style';break;//取消订单
                }
                return style;
            },
            userOperateOrder(url,method,itemTag){
                // console.log(this.orderItem)
                if(method == 'put'){
                    this.xurl.putLoading(url).then((data)=>{
                        if(data.success){
                            this.$emit('getOrderList',this.orderItem,true)
                        } else if (data.errMsg) {
                            this.$root.$emit('toast', {msg: data.errMsg});
                        } else {
                            this.$root.$emit('toast', {msg: '操作失败'});
                        }
                    })
                }else if(method == 'delete'){
                    this.xurl.deleteLoading(url).then((data)=>{
                        if(data.success){
                            this.$emit('getOrderList',this.orderItem,true)
                        } else if (data.errMsg) {
                            this.$root.$emit('toast', {msg: data.errMsg});
                        } else {
                            this.$root.$emit('toast', {msg: '操作失败'});
                        }
                    })
                }
            },
            /*刷新购买价格*/
            refreshBuyBar(orderNum) {
                // console.log(orderNum)
                /*TODO 未修改*/
                /*订单价格为*/
                let that = this;
                let totalGoodsMoney = 0;
                let totalShippingFee = 0;//邮费这个现在暂时好像还没有做（都是免邮的吧）
                this.orderItem.list.forEach((orderItemValue, orderItemIndex) => {
                    /* && orderItemValue.orderState ==0*/
                    if( orderItemValue.selected && orderItemValue.orderState ==0 ) {
                        totalShippingFee += Number(orderItemValue.expressFreight) || 0;
                        totalGoodsMoney += Number(orderItemValue.orderAmount) || 0;
                    }
                });
                totalShippingFee = parseInt((totalShippingFee)*100) / 100;
                totalGoodsMoney = parseInt((totalGoodsMoney)*100) / 100;
                /*修改小计和总计以及优惠信息*/
                let tempObj = {};
                if(this.orderItem.noSelectBtn){
                    this.closeAccountMsg();
                }else{
                    tempObj = {
                        payMoney: {
                            money: totalGoodsMoney,
                            text: '合计'
                        },
                        shippingFee: {
                            isShow: true,
                            money: totalShippingFee,
                        },//邮费、配送费用 ,//邮费、配送费用
                    }
                    this.$emit('refreshBuyBar', tempObj);
                }
            },
            refresh(){
                setTimeout(()=>{
                    /*do*/
                    this.orderItem.curPage = 1;
                    this.$emit('getOrderList',this.orderItem,true)
                    this.$refs.myscroller.finishPullToRefresh();//刷新完毕关闭刷新的转圈圈
                },500)
            },
            infinite(){
                this.$refs.myscroller.finishInfinite(true);//刷新完毕关闭刷新的转圈圈
                setTimeout(()=>{
                    /*do*/
                    this.orderItem.curPage ++;
                    this.$emit('getOrderList',this.orderItem)
                    this.$refs.myscroller.finishPullToRefresh();//刷新完毕关闭刷新的转圈圈
                },500)
            },
        },
        watch: {
            orderProp(val) {
                this.orderItem = Object.assign({}, this.orderItem, val)
                // console.log(val)
            }
        },
        components: {
            'order-item': () => import('./OrderItem'),
            'goods-box': () => import('../../../components/commonComponents/boxItem/GoodsBox'),
            'day-hmsm': () => import('../../../components/commonComponents/timer/DayHMSM'),
            "no-data":()=>import("../../../components/commonActModel/noData/NoData"),
        }
    }
</script>

<style scoped lang="scss">
    .order-list-item /deep/ {
        position: relative;
        min-height: 5.57rem;
        min-height: 88vh;
        min-height:calc(100vh - 1.1rem);
        .buy-item-wrap{
            width: 1.2rem;
            height: 1.7rem;
            margin-right: .05rem;
            .buy-user-left{
                white-space: nowrap;
            }
        }
        .timer{
            padding: 0;
        }
        .time-box{
            display: inline-block;
            background-color: unset;
            border-radius: unset;
            min-width: auto;
            padding: 0;
            height: auto;
            text-align: center;
            line-height: normal;
            font-size: .12rem;
            color: #FF3333;
        }
        .time-unit{
            color: #FF3333;
        }
        .time-boxs{
            padding-left: 0;
        }
        .timer-DayHMSM{
            display: inline-block;
        }
        .no-wcomment{
            top: 2rem;
        }
        /*.cart-citem{*/
            /*padding: .1rem .15rem;*/
        /*}*/
        /*.sub-store-msg{*/
            /*padding: 0 .15rem;*/
        /*}*/
    }

    .sub-store-msg {
        line-height: .24rem;
        align-items: center;
        padding-top: .15rem;
        border-bottom: 0;
    }
    .sub-store-msg-box{
        min-height: 100px;
    }
    .select-wImg {
        margin-right: .05rem;
    }
    .select-img {
        position: relative;
        width: .16rem;
    }
    .disabled-select {
        display: inline-block;
        width: .16rem;
        height: .16rem;
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        border-radius: 50%;
        background-color: #F0F0F0;
    }
    .cart-userheader-wimg {
        height: .24rem;
        width: .24rem;
        position: relative;
        display: inline-block;
        margin-right: .08rem;
    }
    .cart-userheader-img {
        height: .24rem;
        width: .24rem;
        object-fit: unset;
        border-radius: 50%;
    }
    .order-server-wicon{
        padding-left: .15rem;
        border-left: 1px solid #ccc;
        margin-left: .1rem;
        position: relative;
        width: .17rem;
        height: .17rem;
    }
    .order-server-icon{
        width: .17rem;
        height: .17rem;
    }
    .order-wclock{
        position: absolute;
        right: 0;
        top: 0;
        font-size: .12rem;
        color: #FF3333;
        z-index: 1;
    }
    .order-clock{
        position: relative;
        top: 1px;
        width: .11rem;
        height: .11rem;
    }
    .goods-box-wrap{
        overflow:auto;
        white-space: nowrap;
        padding: 0 .1rem;
        .goods-box{
            display: inline-block;
            padding: .05rem;
        }
    }
    .goods-box-wrap /deep/{
        .box-item{
            flex-wrap: nowrap;
        }
    }
    .goods-num-count{
        color: #222;
        font-size: .12rem;
    }
    .operate-btn-right .operate-btn:last-child{
        margin: 0;
    }
    .operate-btn{
        font-size: .12rem;
        display: inline-block;
        -webkit-border-radius: .25rem;
        -moz-border-radius: .25rem;
        border-radius: .25rem;
        padding: .05rem .12rem;
        margin-right: .1rem;
        background-image: linear-gradient(to right,#9EBDFF,#5D89E8);
        color: #fff;
    }
    .operate-btn-wrap{
        padding: .05rem .1rem;
    }
    .operate-btn-left{
        font-size: .12rem;
        color: #666;
    }
    .refund-style{
        background-image: unset;
        background-color: #fff;
        border: 1px solid #5D89E8;
        color: #5D89E8;
    }
    .header-wrap{
        color: #333;
    }
</style>